import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { KehuService } from './kehu.service';
import { KehuDto, CreateUpdateKehuDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { lastValueFrom } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { finalize } from 'rxjs/operators';
import { ExcelExportService } from '../shared/services/excel-export.service';

@Component({
  selector: 'app-kehus',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ThemeSharedModule],
  templateUrl: './kehus.component.html',
  styleUrl: './kehus.component.scss',
  providers: [ListService]
})
export class KehusComponent implements OnInit, OnDestroy {
  kehu = { items: [], totalCount: 0 } as PagedResultDto<KehuDto>;
  createKehuForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedKehuId: string;
  isSaving = false;
  Math = Math; // 添加Math对象以在模板中使用
  
  // 复选框相关变量
  selectedItems: string[] = []; // 存储选中项ID
  isAllSelected = false; // 全选标记
  
  // 企业属性选项
  enterpriseAttributeOptions: string[] = [
    '国有企业',
    '民营企业',
    '外资企业',
    '合资企业',
    '上市公司',
    '私营企业',
    '个体工商户',
    '事业单位',
    '政府机构',
    '非盈利组织',
    '其他'
  ];
  
  // 分页相关变量
  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1; // 最大页数
  visiblePageNumbers: number[] = []; // 可见页码数组
  inputPageNumber: number = 1; // 输入的页码
  
  // 订阅对象
  private subscription: Subscription = new Subscription();
  
  // 添加搜索关键字属性
  nameKeyword = '';
  isSearchMode = false;
  
  // 添加加载状态
  isLoading = false;
  
  // 添加导出状态
  isExporting = false;
  
  constructor(
    public readonly list: ListService,
    private kehuService: KehuService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private modalService: NgbModal,
    private excelExportService: ExcelExportService
  ) {
    this.createKehuForm = this.fb.group({
      name: ['', [Validators.required, Validators.maxLength(100)]],
      address: [''],
      contactPerson: ['', Validators.maxLength(50)],
      phone: ['', Validators.maxLength(20)],
      mobile: ['', Validators.maxLength(20)],
      contact1: ['', Validators.maxLength(50)],
      enterpriseAttribute: ['', Validators.maxLength(50)],
      contractNumber: ['', Validators.maxLength(50)],
      phone1: ['', Validators.maxLength(20)],
      emailAddress: ['', [Validators.maxLength(100), Validators.email]],
      remarks: ['']
    });
  }

  ngOnInit() {
    // 初始化时确保页码是1
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  // 加载数据并处理分页
  loadData() {
    // 确保页面在有效范围内
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.nameKeyword.trim()) {
        return this.kehuService.searchByName(this.nameKeyword, params);
      } else {
        return this.kehuService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false; // 请求结束后，无论成功还是失败，都重置加载状态
            this.selectedItems = []; // 清空选中项
            this.isAllSelected = false; // 重置全选状态
          })
        )
        .subscribe(
          (response: PagedResultDto<KehuDto>) => {
            this.kehu = response;
            // 计算最大页数
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              
              // 如果当前页超出最大页数，则返回到最后一页
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                // 重新加载正确的页数据，但不要造成无限循环
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            
            // 更新页码显示
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }
  
  // 不进行页码检查的数据加载方法，避免循环
  loadDataWithoutCheck() {
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.nameKeyword.trim()) {
        return this.kehuService.searchByName(this.nameKeyword, params);
      } else {
        return this.kehuService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false; // 请求结束后，无论成功还是失败，都重置加载状态
          })
        )
        .subscribe(
          (response: PagedResultDto<KehuDto>) => {
            this.kehu = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }

  // 更新可见页码
  updateVisiblePageNumbers() {
    // 根据当前页码计算显示哪些页码按钮
    // 显示策略：当前页码前后各显示2个，总共最多显示5个页码
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    
    // 始终显示第一页
    pageNumbers.push(1);
    
    // 计算显示的页码范围
    let startPage = Math.max(2, currentPage - 2);
    let endPage = Math.min(this.maxPageCount - 1, currentPage + 2);
    
    // 如果当前页接近开始，调整结束页
    if (currentPage <= 3) {
      endPage = Math.min(5, this.maxPageCount - 1);
    }
    
    // 如果当前页接近结束，调整开始页
    if (currentPage >= this.maxPageCount - 2) {
      startPage = Math.max(2, this.maxPageCount - 4);
    }
    
    // 添加省略号指示符（如果需要）
    if (startPage > 2) {
      pageNumbers.push(-1); // 用-1表示省略号
    }
    
    // 添加中间页码
    for (let i = startPage; i <= endPage; i++) {
      pageNumbers.push(i);
    }
    
    // 添加结尾省略号（如果需要）
    if (endPage < this.maxPageCount - 1) {
      pageNumbers.push(-2); // 用-2表示省略号
    }
    
    // 始终显示最后一页（如果总页数大于1）
    if (this.maxPageCount > 1) {
      pageNumbers.push(this.maxPageCount);
    }
    
    this.visiblePageNumbers = pageNumbers;
    this.inputPageNumber = currentPage;
  }

  // 改变每页显示数量
  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1; // 切换页面大小时重置为第一页
    this.loadData();
  }
  
  // 跳转到指定页码
  goToPage(page: number) {
    if (page >= 1 && page <= this.maxPageCount && page !== this.list.page) {
      this.list.page = page;
      // 调用loadData而不是get()，确保完整的加载流程
      this.loadData();
    }
  }
  
  // 处理页码输入变化
  onPageInputChange(event: Event) {
    const inputElement = event.target as HTMLInputElement;
    const value = inputElement.value.trim();
    let pageNum = parseInt(value, 10);
    
    if (isNaN(pageNum) || pageNum < 1) {
      pageNum = 1;
    } else if (pageNum > this.maxPageCount) {
      pageNum = this.maxPageCount;
    }
    
    this.inputPageNumber = pageNum;
  }
  
  // 处理回车键跳转页码
  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  // 打开创建客户模态框
  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    this.createKehuForm.reset();
    
    // 设置默认值
    this.createKehuForm.patchValue({
      name: '',
      address: '',
      contactPerson: '',
      phone: '',
      mobile: '',
      contact1: '',
      enterpriseAttribute: '',
      contractNumber: '',
      phone1: '',
      emailAddress: '',
      remarks: ''
    });
  }
  
  // 打开编辑客户模态框
  openEditModal(kehuId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedKehuId = kehuId;
    
    // 加载客户数据
    this.kehuService.getById(kehuId).subscribe(
      (kehuData) => {
        this.createKehuForm.patchValue({
          name: kehuData.name,
          address: kehuData.address,
          contactPerson: kehuData.contactPerson,
          phone: kehuData.phone,
          mobile: kehuData.mobile,
          contact1: kehuData.contact1,
          enterpriseAttribute: kehuData.enterpriseAttribute,
          contractNumber: kehuData.contractNumber,
          phone1: kehuData.phone1, 
          emailAddress: kehuData.emailAddress,
          remarks: kehuData.remarks
        });
      },
      (error) => {
        this.toaster.error('加载客户信息失败', '错误');
        console.error('加载客户信息失败', error);
        this.closeModal();
      }
    );
  }

  // 关闭模态框
  closeModal() {
    this.isModalOpen = false;
    this.createKehuForm.reset();
    // 在重置后设置默认空值，避免错误
    this.createKehuForm.patchValue({
      name: '',
      address: '',
      contactPerson: '',
      phone: '',
      mobile: '',
      contact1: '',
      enterpriseAttribute: '',
      contractNumber: '',
      phone1: '',
      emailAddress: '',
      remarks: ''
    }, {emitEvent: false});
  }

  // 保存客户信息
  save() {
    if (this.createKehuForm.invalid) {
      // 标记所有表单控件为dirty，触发验证显示
      Object.keys(this.createKehuForm.controls).forEach(key => {
        const control = this.createKehuForm.get(key);
        control.markAsDirty();
        control.markAsTouched();
      });
      this.toaster.warn('请填写必填字段并修正表单错误', '表单验证');
      return;
    }

    const kehuData = this.createKehuForm.value as CreateUpdateKehuDto;
    this.isSaving = true;
    
    if (this.isEditMode) {
      // 更新客户
      this.kehuService.update(this.selectedKehuId, kehuData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createKehuForm.reset();
          this.loadData(); // 使用loadData替代list.get()
          this.isSaving = false;
          // 显示成功提示
          this.toaster.success('客户信息已成功更新', '成功');
        }, 
        (error) => {
          this.isSaving = false;
          // 显示错误提示
          let errorMessage = '更新客户信息失败';
          if (error && error.error && error.error.message) {
            errorMessage += ': ' + error.error.message;
          }
          this.toaster.error(errorMessage, '错误');
          console.error('更新失败', error);
        }
      );
    } else {
      // 创建客户
      this.kehuService.create(kehuData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createKehuForm.reset();
          this.loadData(); // 使用loadData替代list.get()
          this.isSaving = false;
          // 显示成功提示
          this.toaster.success('客户信息已成功创建', '成功');
        }, 
        (error) => {
          this.isSaving = false;
          // 显示错误提示
          let errorMessage = '创建客户失败';
          if (error && error.error && error.error.message) {
            errorMessage += ': ' + error.error.message;
          }
          this.toaster.error(errorMessage, '错误');
          console.error('创建失败', error);
        }
      );
    }
  }
  
  // 删除客户
  deleteKehu(kehuId: string) {
    this.confirmation.warn(
      '确定要删除此客户吗？', // 更清晰的消息
      '删除确认',
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.kehuService.delete(kehuId).subscribe(
          () => {
            // 检查当前页是否还有数据，如果没有则返回前一页
            if (this.kehu.items.length === 1 && this.list.page > 1) {
              this.list.page--;
            }
            this.loadData(); // 使用loadData替代list.get()
            // 显示成功提示
            this.toaster.success('客户已成功删除', '成功');
          }, 
          (error) => {
            // 显示错误提示
            let errorMessage = '删除客户失败';
            if (error && error.error && error.error.message) {
              errorMessage += ': ' + error.error.message;
            }
            this.toaster.error(errorMessage, '错误');
            console.error('删除失败', error);
          }
        );
      }
    });
  }

  // 添加搜索方法
  searchKehu() {
    if (!this.nameKeyword.trim()) {
      this.resetSearch();
      return;
    }
    
    this.isSearchMode = true;
    this.list.page = 1; // 重置到第一页
    
    // 设置加载中状态
    // this.isLoading = true;
    
    // 根据搜索关键字创建查询
    this.loadData(); // 由于loadData已经考虑isSearchMode，直接调用即可
  }
  
  // 重置搜索
  resetSearch() {
    this.nameKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1; // 重置到第一页
    
    this.loadData(); // 使用已有的loadData方法加载数据
  }

  // 导出选中项到Excel - 新实现
  async exportSelectedItems() {
    if (this.selectedItems.length === 0) {
      this.toaster.info('请先选择要导出的客户', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      console.log('开始导出选中项...', this.selectedItems);
      // 从当前页面数据中筛选选中项
      const selectedData = this.kehu.items.filter(item => 
        item && item.id && this.selectedItems.includes(item.id)
      );
      
      if (selectedData.length === 0) {
        this.toaster.info('在当前页面未找到选中的客户数据', '提示');
        return;
      }
      
      await this.excelExportService.exportKehuToExcel(selectedData, '客户列表_已选择');
      this.toaster.success('导出成功', '提示');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败：' + (error?.message || '未知错误'), '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出当前页数据到Excel - 新实现
  async exportCurrentPage() {
    if (!this.kehu || !this.kehu.items || this.kehu.items.length === 0) {
      this.toaster.info('没有数据可导出', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      console.log('开始导出当前页数据...', this.kehu.items);
      await this.excelExportService.exportKehuToExcel(this.kehu.items, '客户列表_当前页');
      this.toaster.success('导出成功', '提示');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败：' + (error?.message || '未知错误'), '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出所有数据到Excel - 新实现
  exportAllData() {
    if (!this.kehu || !this.kehu.totalCount || this.kehu.totalCount === 0) {
      this.toaster.info('没有数据可导出', '提示');
      return;
    }

    this.isExporting = true;
    
    // 使用批量导出方法
    const fetchAllData = () => {
      return new Promise<KehuDto[]>((resolve, reject) => {
        console.log('开始获取所有数据...');
        this.kehuService.getList({
          maxResultCount: this.kehu.totalCount > 0 ? this.kehu.totalCount : 1000,
          skipCount: 0,
          sorting: ''
        }).subscribe(
          (response) => {
            console.log('获取数据成功:', response);
            resolve(response.items || []);
          },
          (error) => {
            console.error('获取数据失败:', error);
            reject(error);
          }
        );
      });
    };
    
    console.log('准备导出所有数据...');
    
    // 调用批量导出
    this.excelExportService.batchExportToExcel(
      fetchAllData,
      '客户列表_全部',
      (progress) => console.log(`导出进度: ${progress}%`)
    ).then(() => {
      this.toaster.success('全部数据导出成功', '成功');
    }).catch((error) => {
      console.error('导出失败', error);
      this.toaster.error('导出失败：' + (error?.message || '未知错误'), '错误');
    }).finally(() => {
      this.isExporting = false;
    });
  }

  // 全选/取消全选
  selectAll(checked: boolean): void {
    this.isAllSelected = checked;
    this.selectedItems = checked 
      ? this.kehu.items.map(item => item.id) 
      : [];
  }
  
  // 切换单个项的选中状态
  toggleItemSelection(id: string): void {
    const index = this.selectedItems.indexOf(id);
    if (index === -1) {
      this.selectedItems.push(id);
    } else {
      this.selectedItems.splice(index, 1);
    }
    
    // 更新全选状态
    this.isAllSelected = this.kehu.items.length > 0 && 
      this.selectedItems.length === this.kehu.items.length;
  }
  
  // 批量删除选中项
  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.toaster.info('请先选择要删除的客户', '提示');
      return;
    }
    
    this.confirmation.warn(
      '批量删除确认',
      `确定要删除已选中的 ${this.selectedItems.length} 个客户吗？此操作不可撤销。`,
      {
        hideCancelBtn: false,
        yesText: '是',
        cancelText: '否'
      }
    ).subscribe(async (status) => {
      if (status === Confirmation.Status.confirm) {
        this.isLoading = true;
        try {
          // 依次删除选中项
          for (const id of this.selectedItems) {
            await lastValueFrom(this.kehuService.delete(id));
          }
          this.toaster.success(`成功删除 ${this.selectedItems.length} 个客户`, '成功');
          this.selectedItems = [];
          this.isAllSelected = false;
          this.loadData();
        } catch (error) {
          console.error('批量删除失败', error);
          this.toaster.error('部分或全部删除操作失败', '错误');
        } finally {
          this.isLoading = false;
        }
      }
    });
  }
} 